package edu.neu.swc.skynet.service.impl;

import com.alibaba.fastjson.JSON;
import edu.neu.swc.skynet.book.BookInfo;
import edu.neu.swc.skynet.book.BookShow;
import edu.neu.swc.skynet.common.SearchParams;
import edu.neu.swc.skynet.common.TableId;
import edu.neu.swc.skynet.document.SkyNetBookDoc;
import edu.neu.swc.skynet.repository.SkyNetBookRepository;
import edu.neu.swc.skynet.service.IBookService;
import edu.neu.swc.skynet.vo.PageBookShow;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BookServiceImpl implements IBookService {

    private final SkyNetBookRepository bookRepository;

    public BookServiceImpl(SkyNetBookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    @Override
    public PageBookShow getBookShowByName(SearchParams searchParams) {

        Integer page = searchParams.getPage();
        String bookName = searchParams.getKey();

        if(page <= 1){
            page = 1; // 默认是第一页
        }

        // 这里分页的规则（可以自由修改）：一页包含10条数据，按照商品ID倒序排列
        Pageable pageable = PageRequest.of(
                page - 1,
                10,
                Sort.by("bookPrice").descending()
        );

        Page<SkyNetBookDoc> skyNetBookDocPage =
                bookRepository.findByBookName(bookName, pageable);

        boolean hasMore = skyNetBookDocPage.getTotalPages() > page;

        List<BookShow> bookShows = skyNetBookDocPage.getContent().stream()
                .map(SkyNetBookDoc::toBookShow)
                .collect(Collectors.toList());

        return new PageBookShow(
                bookShows,
                hasMore
        );
    }

    @Override
    public List<BookInfo> getBookInfoById(TableId tableId) {
        //1. 解析 Id 列表
        //这里不能从缓存中取数据，需要访问数据库
        List<Long> ids = tableId.getIds().stream()
                .map(TableId.Id::getId)
                .collect(Collectors.toList());

        log.info("get books by ids:[{}]", JSON.toJSONString(
                ids
        ));

        List<SkyNetBookDoc> skyNetBookDocs = new ArrayList<>();

        ids.forEach(id -> skyNetBookDocs.add(bookRepository.findById(id)));

        return skyNetBookDocs.stream()
                .map(SkyNetBookDoc::toBookInfo)
                .collect(Collectors.toList());
    }
}
